package dao;

import java.rmi.RemoteException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import dto.Account;
import service.ChatClientService;

public class ContactListDAO extends AbstractDAO {

    /**
     * Return the ContactList Fro each user from DB.
     */
	public Vector<Account> getContactList(Account account) {
		Vector<Account> myContactList = null;
		Account temp;
		int contactId;
		try {
			String mail = account.getEmail();

			PreparedStatement ps = connection
					.prepareStatement("select * from contactlist where accout IN (select id from account where email= ?)");
			ps.setString(1, mail);

			ResultSet rs = ps.executeQuery();

			AccountDAO accountDAO = new AccountDAO();
			if (rs.next()) {
				myContactList = new Vector<Account>();
				do {
					contactId = rs.getInt("contact");
					temp = accountDAO.getAccount(contactId);
					myContactList.add(temp);
				} while (rs.next());
			}
		} catch (SQLException ex) {
			Logger.getLogger(ContactListDAO.class.getName()).log(Level.SEVERE,
					null, ex);
		}
		return myContactList;
	}
        /**
         * Get Account 's details by mail.
         */
        public Account getAccount(String mail) {
		Account account = null;

		try {
			PreparedStatement ps;

			ps = connection
					.prepareStatement("select * from account where email = ?");
			ps.setString(1, mail);
			ResultSet rs = ps.executeQuery();

			if (rs.next()) {
				account = new Account();
				account.setFirstName(rs.getString("firstname"));
				account.setLastName(rs.getString("lastname"));
				account.setEmail(rs.getString("email"));
				account.setStatusMsg(rs.getString("status_msg"));
				account.setGender(rs.getString("gender"));
				account.setCountry(rs.getString("country"));
			}

		} catch (SQLException ex) {
			Logger.getLogger(ContactListDAO.class.getName()).log(Level.SEVERE,
					null, ex);
		}

		return account;

	}
        /**
         * Store the new contact in DB.
         */
        
    public void addContact(Account requestSender, Account requestReciever) {
        try {
            String senderEmail = requestSender.getEmail();
            String recieverEmail = requestReciever.getEmail();
            AccountDAO accountDAO = new AccountDAO();
            int senderId = accountDAO.getAccountId(senderEmail);
            int recieveId= accountDAO.getAccountId(recieverEmail);
            
            //check if already exists
            
            PreparedStatement ps = connection.prepareStatement("insert into contactlist values(?,?) on duplicate key update contact = contact");
            ps.setInt(1, senderId);
            ps.setInt(2, recieveId);            
            PreparedStatement ps2 = connection.prepareStatement("insert into contactlist values(?,?) on duplicate key update contact = contact");
            ps2.setInt(1, recieveId);
            ps2.setInt(2, senderId);
            
            ps.executeUpdate();
            ps2.executeUpdate();
    
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    /** 
     * Remove a contact from contact list stored in DB.
     * 
     */
	public Boolean removeContact(String mail, Account accountAccount) {
		Boolean ret = false;
		Account Contactaccount = null;

		int contactId = 0;
		int accountId = 1;

		int result;
		// Check if it exist in DB, If So Add it to contact List .. If Not,
		// return false.
		AccountDAO accountDAO = new AccountDAO();
		Contactaccount = accountDAO.getAccount(mail);
		if (Contactaccount != null) {
			try {
				// / for Contact.
				PreparedStatement ps = connection
						.prepareStatement("select id from account where email=?");
				ps.setString(1, mail);
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					contactId = rs.getInt("id");
				}
				// /// For account [original client.]
				PreparedStatement ps2 = connection
						.prepareStatement("select id from account where email=?");
				ps2.setString(1, accountAccount.getEmail());
				ResultSet rs2 = ps2.executeQuery();
				if (rs2.next()) {
					accountId = rs2.getInt("id");
				}

				PreparedStatement ps3 = connection
						.prepareStatement("Delete from contactlist where accout=? AND contact= ?");
				ps3.setInt(1, accountId); // ////***Needs Update *//
				ps3.setInt(2, contactId);

				result = ps3.executeUpdate();

				if (result != 0)
					ret = true;
			} catch (SQLException ex) {
				Logger.getLogger(ContactListDAO.class.getName()).log(Level.SEVERE,
						null, ex);
			}
		}

		return ret;
	}
        /**
         * Store FriendRequest in DB.
         */
        public void storeFriendrequest(String sendermail,String receiver)
        {
        try {
            PreparedStatement ps = connection.prepareStatement("insert into pinnedfriendrequest values (?, ?)");
        
            ps.setString(1, sendermail);
            ps.setString(2, receiver);
            
            ps.executeUpdate();
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        }
        /**
         * Store FriendRequest Reply in DB.
         */
        public void storeFriendrequestReply(String userWhoAddmail,String userWhoReplymail, int reply)
        {
            try {
            PreparedStatement ps = connection.prepareStatement("insert into pinnedfriendrequestconfirmation values (?, ?, ?)");
    
            ps.setString(1, userWhoReplymail);
            ps.setString(2, userWhoAddmail);
            ps.setInt(3, reply);
            
            ps.executeUpdate();
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
            
        }
        /** 
         * Check if there is any PinnedFriendRequest for client.
         * 
         */
        public void checkPinnedFriendRequest(ChatClientService clientService)
        {
        try {
            Account account=clientService.getLoggedInAccount();
            String recieverMail= account.getEmail();
            
            PreparedStatement ps= connection.prepareStatement("select * from pinnedfriendrequest where receiveremail= ?");
            ps.setString(1, recieverMail);
            
            ResultSet rs = ps.executeQuery();
            
            if(rs.next())
            {
                do{
                String senderMail = rs.getString("senderemail");
                clientService.friendRequest(getAccount(senderMail));
                } while(rs.next());
                
                ps = connection.prepareStatement("delete from pinnedfriendrequest where receiveremail = ?");
                ps.setString(1, recieverMail);
                
                ps.executeUpdate();
                
                       
                
            }
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
            
            
        }
        /** 
         * Check if there is any PinnedFriendRequest Reply for client.
         * 
         */
        public void checkPinnedFriendRequestReply(ChatClientService clientService)
        {
        try {
            Account account=clientService.getLoggedInAccount();
            String mail= account.getEmail();
            PreparedStatement ps= connection.prepareStatement("select * from pinnedfriendrequestconfirmation where confirmed_to= ?");
            ps.setString(1, mail);
            
            
            ResultSet rs = ps.executeQuery();
            
            if(rs.next())
            {
                do{
                String senderMail = rs.getString("confirmed");
                int reply= rs.getInt("reply");
                clientService.friendRequestReply(getAccount(senderMail), reply);
                } while(rs.next());
                       
                ps = connection.prepareStatement("delete from pinnedfriendrequestconfirmation where confirmed_to = ?");
                ps.setString(1, mail);
                
                ps.executeUpdate();
            }
            
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
            
        }
}
